package get.data;

import java.util.ArrayList;
import java.util.Random;

import drag.and.drop.DrawView;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.AbsoluteLayout;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.FrameLayout.LayoutParams;

class HotNode{
	
	int coordx;
	int coordy;
	int temp;
	
	HotNode(int coordx, int coordy, int temp){
		this.coordx = coordx;
		this. coordy = coordy;
		this.temp = temp;
	}	
}

public class ViewMap extends Activity{
	
	   ImageView image;
	   int[][] temp; 
	   int w,h,room_width, room_height,mintemp;
	   ArrayList< HotNode > hotpoints;
	   public void onCreate(Bundle savedInstanceState) {
	        super.onCreate(savedInstanceState);
	        setContentView(R.layout.view_map);
			hotpoints = new ArrayList<HotNode>();			
	        AbsoluteLayout layer = (AbsoluteLayout) findViewById(R.id.layer);
	        image = (ImageView) findViewById(R.id.im);
	        image.setKeepScreenOn(true);

	        //w pixeli fac room_width metri
	        w = 320;
	        h = 450;
	        mintemp = 100;
	        
	        int room_w = 10;
	        int room_h = 5;
	     
	        temp = new int[w][h];

	        Main.db.close();
    		String myPath = DatabaseHandler.DB_PATH+ DatabaseHandler.DB_NAME;
    		Main.db = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);

	        
			if(DatabaseHandler.checkDataBase(Main.db) == false){
				Intent newIntent = new Intent(ViewMap.this,drag.and.drop.SetNodesPosition.class);
				startActivity(newIntent);
				finish();
			}
			else{
					   
				ArrayList<DrawView> objects = new ArrayList<DrawView>();
				for(int i=0;i<Main.nodes.size();i++){
					int coordx = 0;
					int coordy = 0;
					//put object at specific coordinates
					//get coordinates
					String sql = "SELECT * FROM "+ DatabaseHandler.NODES + " WHERE id='"+Main.nodes.get(i).GetId()+"'";
					Cursor c = Main.db.rawQuery(sql, null);
					System.out.println(sql);
					System.out.println(c.getCount());
					c.moveToFirst();
					if (c != null) {
						coordx = c.getInt(3);
						coordy = c.getInt(4);
						System.out.println("**"+coordx+" "+coordy+""); 			
					}
					c.close();
					String tmp = NodeAdaptor.URLresponse(Main.nodes.get(i).GetTemp()).trim();
					int ftemp = (int) Float.parseFloat(tmp);
					System.out.println(coordx+" "+coordy+" "+ tmp);
					if(Main.nodes.get(i).GetStatus()==true)
						hotpoints.add(new HotNode(coordx, coordy, ftemp));

					DrawView dw;
					
					dw = new DrawView(this,Main.nodes.get(i).GetId(),coordx,coordy,ftemp);
					dw.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
					dw.setId(i);			
					objects.add(dw);
					}
						
			    
				for(int k=0;k<objects.size();k++){
					layer.addView(objects.get(k));
				}
			}
			
			Button bt = (Button) findViewById(R.id.edit);
			bt.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View arg0) {
					Intent newIntent = new Intent(ViewMap.this,drag.and.drop.SetNodesPosition.class);
					startActivity(newIntent);	
					finish();
				}
			});
			
		    layer.setOnTouchListener(new OnTouchListener() {
		        public boolean onTouch(View v, MotionEvent ev) {
		        	
		            System.out.println("Touch at " + ev.getX() + ", " + ev.getY());    

		        	String value = "";
					//querry the nodes around the touch point with a certain precision
		        	
			        Main.db.close();
		    		String myPath = DatabaseHandler.DB_PATH+ DatabaseHandler.DB_NAME;
		    		Main.db = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
		    		int precision = 40;
					String sql = "SELECT * FROM "+ DatabaseHandler.NODES + " WHERE coordx<"+(int)(ev.getX()+precision)+" AND coordx>"+(int)(ev.getX()-precision) 
						+" AND coordy<"+(int)(ev.getY()+precision)+" AND coordy>"+(int)(ev.getY()-precision);
					Cursor c = Main.db.rawQuery(sql, null);
					int cnt = c.getCount();
					c.moveToFirst();
					for(int i=0;i<c.getCount();i++) {
						String ip = c.getString(2);//look for ip
						int idx = get_index_by_ip(ip);
						if(idx>=0)
							value = value + idx+" ";
						c.moveToNext();
					}
					c.close();
					System.out.println(value);

					if(cnt>0){
			            Intent newIntent = new Intent(ViewMap.this,NodeData.class);
			            newIntent.putExtra("indexs", value);
						startActivity(newIntent);
			            try {
							Thread.sleep(1000);
						} catch (InterruptedException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						finish();
					}
		            return true; 
		        }
		    });
			
			create_temperature_map();
			
			

	   }
	   
	    private int get_index_by_ip(String ip){
	    	
	    	for(int i=0;i<Main.nodes.size();i++){
	    		if(Main.nodes.get(i).GetAdd().compareTo(ip)==0)
	    			return i;
	    	}
	    	return -1;
	    }

		public void onStop ()
	    {
	    	super.onStop();
	    	Main.db.close();
	    }
		
	    private void create_temperature_map() {

	    	Random rand = new Random();
	        System.out.println("Dimensiuni: "+w+" "+h);
	        
	        System.out.println("HotNodes:");
	        for(int i=0;i<hotpoints.size();i++)
	        	System.out.println(hotpoints.get(i).coordx+" "+hotpoints.get(i).coordy+" "+hotpoints.get(i).temp);
	        
	        int[] byteArray = new int[w*h];	        
	        int k=0;
	        int R,G,B;
	        float a,b;
	        System.out.println("Size: "+ hotpoints.size());
        	for(int i=0;i<h;i++){
        		String temps="";
	    		for(int j=0;j<w;j++){
	    			int t = get_temperature(i,j,hotpoints);
	    			if(t<100)
	    				t=100;
	    			temps = temps + t+" ";
	    			//System.out.println("->"+i+" "+j+" "+t);
	    			R = 255;	    			
	    			a=(float) -1;
    				b= 357;
    					    				
    				G=(int) (a*t+b);
    				B=(int) (a*t+b);
	    			byteArray[k++] = 0x88000000 | (R << 16) | (G << 8) | B;
	    			
	    		}
	    		//System.out.println(temps);
        	}
	        
	        Bitmap bm = Bitmap.createBitmap(byteArray, w, h, Bitmap.Config.ARGB_8888); 
	        image.setImageBitmap(bm);
		}

		private int get_temperature(int x, int y,ArrayList<HotNode> hotpoints2) {
			int t;
			float sum=0, imp=0;
			int d1; 
			for(int i=0;i<hotpoints.size();i++){ 
			//for(int i=0;i<1;i++){
				int hpy = hotpoints.get(i).coordx;
				int hpx = hotpoints.get(i).coordy;
				t = hotpoints.get(i).temp;
				//distance in pixels
				d1 = (int) Math.sqrt((x-hpx)*(x-hpx)+(y-hpy)*(y-hpy));
				//d1 = (int) (x-hpx)*(x-hpx)+(y-hpy)*(y-hpy);	
				if(d1==0)
					return t;
				if(t>d1/2)
					sum += (t-d1/2);

				imp=1;

			}
			
			//return (int)(sum/imp);
			return (int)(sum/hotpoints.size());
		}
}
